'use strict';

App.controller('addPublishController', ['$rootScope', '$scope', '$state', 'Page', function($rootScope, $scope, $state, Page) {
	if($state.params.model== null || $state.params.model == ''){
		 $state.go('publish', null);
		 return;
	}
	
	 $scope.customerId = $rootScope.user.sourceId;// 根据登录用户获得客户id
	 $scope.timeQuery = {};
    
    $scope.checkResources = new Map();
    $scope.busResources = new Map();// 车辆资源
    $scope.stopResources = new Map();// 站点资源
    
    //点击编辑，进入add页面
    $scope.publishBill = $state.params.model;
    if($scope.publishBill.addFlag) {
    	  $scope.publishBill = {};// 添加
    } else {
    	$scope.checkResources = new Map();
        $scope.busResources = new Map();
        $scope.stopResources = new Map();
        $scope.addFlag = false; //新增标志
        //修改，将车牌号变成超链接
        $scope.updateHrefFlag = true;
        Page.ajaxPostQuiet('publishBill/queryBillDetails.do', {billId : $scope.publishBill.billId}, function (resp) {
            var data = resp.data.array;
            $scope.mediaTypeMap = new Map();
            $scope.bidFiles = resp.data.fileArray;
            $scope.bidImgs = resp.data.imgArray;
            for (var i = 0; i < data.length; i++) {
                if($scope.mediaName == undefined || $scope.mediaName == "") {
                    $scope.mediaName = data[i].mediaName;
                    $scope.publishBill.mediaType = data[i].mediaType;
                }
                data[i].billStartDate = data[i].billStartDate.split(" ")[0];
                data[i].billEndDate = data[i].billEndDate.split(" ")[0];
                $scope.checkResources.put(data[i].resourceId,data[i]);
            }
            if($scope.publishBill.billType == "1") {
                $scope.busResources = angular.copy($scope.checkResources);
            } else {
                $scope.stopResources = angular.copy($scope.checkResources);
            }
            
            //获取原纪录
            var file = [];
            $scope.bidImg ={};
            $scope.bidImg.file = file.concat($scope.bidImgs);
            
            $scope.bidFile ={};
            $scope.bidFile.file = file.concat($scope.bidFiles);
           // $scope.billAddModal.show();
        });
    }
    
    
	$scope.addPublish = {
		    //查询mediaType
		    changeBillType : function() {
		    	if($scope.publishBill.billType == undefined){
		    		$scope.mediaTypes = [];
		    	}else {
		    		Page.ajaxPostQuiet('mediaType/getMediaTypesByParentId.do', {parentId : $scope.publishBill.billType}, function (resp) {
			            $scope.showMediaType = true;
			            $scope.mediaTypes = resp.data
			            // 上刊类型改变 清空所有选择的资源
			            $scope.checkResources = new Map();
			            $scope.busResources = new Map();
			            $scope.stopResources = new Map();
			        });
		    	}
		    },
		  //查询mediaType
		    changeMediaType : function() {
		            // 上刊类型改变 清空所有选择的资源
		            $scope.checkResources = new Map();
		            $scope.busResources = new Map();
		            $scope.stopResources = new Map();
		    },
		    
			addPublishDetail : function(){
	            if($scope.publishBill.billType == undefined || $scope.publishBill.billType == "") {
	                Page.notice("请选择上刊类型!");
	                return;
	            }
	            if($scope.publishBill.mediaType == undefined || $scope.publishBill.mediaType == "") {
	                Page.notice("请选择媒体类型!");
	                return;
	            }
	            $scope.modalBillId = "";
	            $scope.clickAddFlag = true;
	            $scope.updateClickFlag = false;
	            $(".resourceCheckbox").each(function(index,element){
	                if(element.checked) {
	                    element.checked = false;
	                }
	            });
	            
	            $scope.addFlag = true;
	            $scope.query();
	            $scope.billDetailsModal.show();
			},
			// 最终确认完成
			lastSure : function() {
				
				var oDate = new Date(); // 实例一个时间对象；
				var year = oDate.getFullYear(); // 获取系统的年；
				var month = oDate.getMonth()+1; // 获取系统月份，由于月份是从0开始计算，所以要加1
				var day = oDate.getDate(); // 获取系统日，
				var hour = oDate.getHours(); // 获取系统时，
				var minute = oDate.getMinutes(); // 分
				var second = oDate.getSeconds(); // 秒
				var millisecond = oDate.getMilliseconds(); // 获取当前毫秒数(0-999)
				
			/*	var aa2 = oDate.toLocaleDateString();     //获取当前日期
				var mytime=oDate.toLocaleTimeString();     //获取当前时间
				var aa3 = oDate.toLocaleString( );        //获取日期与时间
*/				
				if(month<10){
					month = "0"+month;
				}
				if(day<10){
					day = "0"+day;
				}
				if(hour<10){
					hour = "0"+hour;
				}
				if(minute<10){
					minute = "0"+minute;
				}
				if(second<10){
					second = "0"+second;
				}
				if(millisecond<10){
					millisecond = "00"+millisecond;
				}
				
			    var now = ""+year + month + day + hour +minute + second + millisecond;
				
				$scope.publishBill.billNo = now;
				
		    	var param = {};
		    	param.busResources = $scope.busResources.elements;
		    	param.stopResources = $scope.stopResources.elements;
		    	param.customerId = $scope.customerId;// 客户id
		    	param.billNo = $scope.publishBill.billNo;
		    	param.billType = $scope.publishBill.billType;
		    	param.billId = $scope.publishBill.billId;
		    	param.billContent = $scope.publishBill.content;
		    	param.billPublishTime = $scope.publishBill.publishTime;
		    	param.billPublishOffTime = $scope.publishBill.publishOffTime;
		    	 if($scope.bidFile != undefined) {
		    		 param.bidFiles = $scope.bidFile.file;// 上刊资料
		         }else {
		        	 param.bidFiles = [];
		         }
		    	 if($scope.bidImg != undefined) {
		    		 param.bidImgs = $scope.bidImg.file;
		         }else {
		        	 param.bidImgs = [];
		         }
		    	 if($scope.busResources.elements.length==0 && $scope.stopResources.elements.length==0){
		    		 Page.notice("上刊单资源为空,请选择具体的资源数据!");
		    		 return false;
		    	 }else if(param.bidFiles.length==0) {
		    		 Page.notice("广告资料为空,请选择广告相关的资料文件!");
		    		 return false;
		    	 }else if(param.bidImgs.length==0) {
		    		 Page.notice("广告样刊为空,请选择广告相关的样刊文件!");
		    		 return false;
		    	 } else if(param.billPublishTime == undefined) {
		    		 Page.notice("上刊单开始时间不能为空!");
		    		 return false;
		    	 } else if(param.billPublishOffTime == undefined) {
		    		 Page.notice("上刊单截止时间不能为空!");
		    		 return false;
		    	 } else {
		    		 Page.ajaxPost('publishBill/saveBillDetails.do',param, function (resp) {
		    	            var data = resp.data;
		    	            if(data.flag){
		    	            	Page.notice("保存成功!");
		    	            	$state.go('publish', null);
		    	            }else {
		    	            	Page.notice(data.msg);
		    	            }
		    	           
		    	        });
		    	 }
		    	
		    },
		    
		    callBack : function() {
		    	 window.history.back();
		    }
	}
	
    $scope.fileModal = {
    		deleteFile : function(file,flag){// flag 1:资料 2：样刊
    			var files = flag == 1? $scope.bidFile.file:$scope.bidImg.file;
    			 for (var i = 0; i < files.length; i++) {
    				 if(files[i].path.indexOf(file.path)>-1){
    					 if(flag == 1){
    						 $scope.bidFile.file.splice(i,1);
    					 }else {
    						 $scope.bidImg.file.splice(i,1);
    					 }
    				 }
    			 }
    		},
		  downloadFile : function(filePath) {
	      	document.location.href = "publishBill/downLoadFile.do?publishFile="+filePath;
	      }
    }
    
	
	  $scope.billDetailsModal = {
	        onOkClick : function() {// 明细弹框，选择资源后点击确定
	            $scope.busResources = new Map();
	            $scope.stopResources = new Map();
	            var checkResources = angular.copy($scope.checkResources);
	            $scope.mediaTypeMap = new Map();

	            if($scope.checkResources != undefined && $scope.checkResources.elements.length > 0) {
	                for (var i = 0; i < $scope.checkResources.elements.length; i++) {
	                    if($scope.mediaTypeMap.get($scope.checkResources.elements[i].value.mediaType) == undefined) {
	                        $scope.mediaTypeMap.put($scope.checkResources.elements[i].value.mediaType,
	                            $scope.checkResources.elements[i].value.mediaName);
	                    }
	                }
	            }
	            if($scope.checkResources.elements.length > 0) {
	                if($scope.publishBill.billType == "1") { // 车辆
	                    $scope.busResources = angular.copy($scope.checkResources);
	                } else {
	                    $scope.stopResources = angular.copy($scope.checkResources);
	                }
	            }
	            //$scope.makeTure = true;
	            $scope.billDetailsModal.hide();
	        },
	      //checkBox点击事件
	        checkSource : function($event,data){
	        	if($event.target.checked) {
		            $scope.checkResources.put(data.resourceId,data);
		        } else {
		            $scope.checkResources.remove(data.resourceId);
		        }
		    },
		    showUpdateModal : function(value) {
		        $scope.modalResourceId = value.resourceId;
		        $scope.content = value.content;
		        $scope.modalBillId = value.billId;
		        $scope.updateClickData = value;
		        //是否点击修改超链接
		        $scope.updateClickFlag = true;
		        $scope.billDetailsModal.show();
		        $scope.query();
		    },
	        onHidden : function() {
	            if($scope.modalResourceId != undefined || $scope.modalResourceId != "") {
	                $scope.modalResourceId = "";
	            }
	            $scope.monthWatch();// 注销监听的函数
	        }
	    }
	
	
	// 资源删除
	$scope.removeResources = function(value) {
        $scope.checkResources.remove(value.resourceId);
        if($scope.publishBill.billType == "1") {//车辆
            $scope.busResources.remove(value.resourceId);
        } else {
            $scope.stopResources.remove(value.resourceId);
        }
    }
	
	
	 /* $scope.monthChange = function(resourceName,status,month) {
	        $scope.query(resourceName,status,month);
	    }*/
	
		//采用监听的方式
	$scope.monthWatch = $scope.$watch('scheduleModal.month', function (newValue, oldValue, $scope) {
        if (newValue == undefined || newValue == "") {
            return;
        }
        $scope.query();
	 });
	  
	 $scope.scheduleModal  = {};
	 $scope.scheduleModal.month = "";
	  
	 $scope.query = function(resourceName,lastOrNext, monthOrYear) {
        var param = {};
        param.month = $scope.scheduleModal.month;// 当前月份
        param.lastOrNext = lastOrNext;// -1：上一月 上一年 1：下一月 下一年
        param.monthOrYear = monthOrYear;// 1:年 2：月
        param.pageIndex = 0;
        param.pageSize = 10;
        //param.resourceName = resourceName;
        param.startDate = $scope.timeQuery.startDate;
        param.endDate = $scope.timeQuery.endDate;
        param.modalResourceId = $scope.modalResourceId;
        param.modalBillId = $scope.modalBillId;
        param.customerId = $scope.customerId;// 客户id
        param.billType = $scope.publishBill.billType;
        param.mediaId = $scope.publishBill.mediaType;
        Page.ajaxPost('schedule/queryBillSources.do', param, function(resp) {
            $scope.months = resp.data.months;
            $scope.days = resp.data.daysArray;
            $scope.dataArray = resp.data.dataArray;
            $scope.monthSelect = resp.data.currentMonth;
            $scope.lastYear = resp.data.lastYear;
            $scope.nextYear = resp.data.nextYear;
            $scope.totalPages = resp.data.totalPages;
            $scope.currentMonth = resp.data.currentMonth;
            $scope.scheduleModal.month = resp.data.currentMonth;
            // 调用分页
            laypage({
                cont : 'page_bar',
                pages : $scope.totalPages,// 得到总页数
                skin : '#3E97E4',
                skip : true, // 是否开启跳页
                prev : '<', // 若不显示，设置false即可
                next : '>', // 若不显示，设置false即可
                groups : 5, //连续分页数
                curr: 1, //初始化当前页
                jump : function(obj,first) {// 触发分页后的回调
                    /*obj是一个object类型。包括了分页的所有配置信息。
                     first一个Boolean类，检测页面是否初始加载。非常有用，可避免无限刷新。*/
                    if(!first){
                        var param = {};
                        param.month = $scope.currentMonth;// 当前月份
                        param.pageIndex = obj.curr - 1;
                        param.pageSize = 10;
                        Page.ajaxPost('schedule/queryBillSources.do', param, function(
                            resp) {
                            $scope.months = resp.data.months;
                            $scope.days = resp.data.daysArray;
                            $scope.dataArray = resp.data.dataArray;
                            $scope.monthSelect = resp.data.currentMonth;
                            $scope.lastYear = resp.data.lastYear;
                            $scope.nextYear = resp.data.nextYear;
                            $scope.totalPages = resp.data.totalPages;
                            $scope.currentMonth = resp.data.currentMonth;
                            $scope.scheduleModal.month = resp.data.currentMonth;
                        });
                    }
                }
            })
        });
    }
	
}]);